package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.PageResult;
import cn.wolfcode.query.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public PageInfo<Employee> query(QueryObject qo) {
     /*   int totalCount = employeeMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult<Employee>(qo.getCurrentPage(), qo.getPageSize(), 0, Collections.EMPTY_LIST);
        }*/
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> list = employeeMapper.queryForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public Employee login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if (employee == null) {
            throw new RuntimeException("账号或密码错误");
        }
        return employee;
    }

    @Override
    public String selectPwdByEmpId(Long id) {
        String pwd = employeeMapper.selectPwdByEmpId(id);
        return pwd;
    }

    @Override
    public void updatePwdByEmpId(String newPassword,Long id) {
        employeeMapper.updatePwdByEmpId(newPassword,id);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
        //删除中间表

    }


    /**
     * 验证用户名是否存在
     * @param name
     * @return
     */
    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public void updateStatusByEmpId(boolean status,Long id) {
        employeeMapper.updateStatusByEmpId(status,id);
    }

    /**
     * 文件导出
     * @return
     */
    @Override
    public Workbook exportXls() {
        //创建 Excel文件
        Workbook wb = new HSSFWorkbook();
        //创建表格
        Sheet sheet = wb.createSheet("员工名单");
        //创建表格中的第一行
        Row row = sheet.createRow(0);
        //创建第一行中的单元格并设置内容
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //获取员工的所有数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            //获取每一个员工对象
            Employee employee = employees.get(i);
            //创建每一行(从第二行开始)
            row = sheet.createRow(i + 1);
            //创建每一行中的单元格并设置内容
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    /**
     * 导入功能
     * @param file
     */
    @Override
    public void importXls(MultipartFile file) throws IOException {
        //创建一个Excel表格,将获取的上传文件的输入流传进去
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //获取表格中的第一张表
        Sheet sheet = wb.getSheetAt(0);
        //获取表格中的行数---lastRowNum表示的索引值
        int lastRowNum = sheet.getLastRowNum();
        //遍历这些行数(只需要从第二行遍历就行,第一行表示的是标题)
        for (int i = 1; i <=lastRowNum ; i++) {
            //新建员工对象,用来封装上传文件中的内容
            Employee employee = new Employee();
            //获取每一行
            Row row = sheet.getRow(i);
            //将每一行中的内容封装进employee对象中
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            //如果Excel表格中的单元格格式是常规类型或数字类型,输入的数字那么取的话需要用number类型取,然后在转成int类型
            employee.setAge((int) row.getCell(2).getNumericCellValue());
            //如果Excel表格中的单元格格式是文本类型,输入的数字那么取的话需要用value类型取,然后在转成int类型
//            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //也可以判断非空之后再设置给employee对象,避免转换时,出现空指针异常
            //设置默认密码为1
            employee.setPassword("1");
            //保存(为了使用MD5进行加密,调用save方法)
            this.save(employee,null);
            System.out.println("================");
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {

        return employeeMapper.selectByRoleSn(sns);
    }


    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());

        //先保存员工
        employeeMapper.insert(employee);
        //先判断ids是否为空
        if (ids != null&&ids.length>0) {
        //关联员工和角色的关系(添加新关系),谁作为多对多的主表,谁来维护关系
        //第一种方法:使用forEach遍历
        /*for (Long rid : ids) {
            employeeMapper.insertRelation(employee.getId(),rid);
        }*/
        //第二种方法:动态拼接sql(在sql中使用foreach)
        employeeMapper.insertRelation(employee.getId(),ids);
        }
    }

    @Override
    public void update(Employee employee,Long[] ids) {
        //更新操作需要维护中间表,先删除旧关系,在添加新关系
        employeeMapper.deleteRelation(employee.getId());
        if (ids != null&&ids.length>0) {
            employeeMapper.insertRelation(employee.getId(),ids);
        }
        employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public void delete(Long id) {
        //删除关系
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }


}
